package component.dispatcher;

import analyser.node.AbstractAnalyser;
import kit.AnalyserIndexerKit;
import model.MibModule;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NodeAnalyseDispatcher implements INodeAnalyseDispatcher {
    protected Map<String, Class<? extends AbstractAnalyser>> typeAnalyserMap = new HashMap<>();
    protected MibModule module;
    protected NodeAnalyseDispatcher next;

    public NodeAnalyseDispatcher(MibModule module) {
        this(module, null);
    }

    public NodeAnalyseDispatcher(MibModule module, NodeAnalyseDispatcher next) {
        this.next = next;
        this.module = module;
        this.despatch();
    }

    @Override
    public AbstractAnalyser tryAssign(String type, AnalyserIndexerKit kit, List<String> txtList) {
        if (type == null)
            throw new IllegalArgumentException();
        if (typeAnalyserMap.containsKey(type)){
            try {
                return typeAnalyserMap.get(type)
                        .getConstructor(AnalyserIndexerKit.class, List.class)
                        .newInstance(kit, txtList);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return next == null ? null : next.tryAssign(type, kit, txtList);
    }

    protected void despatch(){}
}
